﻿Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client
Imports Microsoft.TeamFoundation.Server

Public Class TFSProject
  Private Sub New()

  End Sub


  Public Shared Function Areas(ByVal TFSServerName As String, ByVal TFSProjectName As String) As Dictionary(Of String, String)
    Return GetHierarchy(TFSServerName, TFSProjectName, "ProjectModelHierarchy", "Area")

  End Function

  Public Shared Function Iterations(ByVal TFSServerName As String, ByVal TFSProjectName As String) As Dictionary(Of String, String)
    Return GetHierarchy(TFSServerName, TFSProjectName, "ProjectLifecycle", "Iteration")

  End Function

  Private Shared Function GetHierarchy(ByVal TFSServerName As String, ByVal TFSProjectName As String, ByVal hierarchyName As String, ByVal doNotInclude As String) As Dictionary(Of String, String)
    Dim tfsServer As TeamFoundationServer = TeamFoundationServerFactory.GetServer(TFSServerName)
    tfsServer.Authenticate()

    Dim commonStructure As ICommonStructureService = DirectCast(tfsServer.GetService(GetType(ICommonStructureService)), ICommonStructureService)

    Dim project As ProjectInfo = commonStructure.GetProjectFromName(TFSProjectName)
    Dim results = New Dictionary(Of String, String)

    For Each Node As NodeInfo In commonStructure.ListStructures(project.Uri)
      If Node.StructureType = hierarchyName Then
        Dim nodeElement As Xml.XmlElement = commonStructure.GetNodesXml(New String() {Node.Uri}, True)
        AddChildNodes(Node.Name, nodeElement.ChildNodes(0), results, doNotInclude)
      End If
    Next

    Return results

  End Function


  Private Shared Sub AddChildNodes(ByVal parentPath As String, ByVal parentNode As Xml.XmlNode, ByVal results As Dictionary(Of String, String), ByVal doNotInclude As String)
    If doNotInclude.ToUpper <> parentPath.ToUpper Then
      results.Add(parentPath, parentNode.Attributes("NodeID").Value)
    End If

    If parentNode.ChildNodes(0) Is Nothing Then Return

    For Each Node As Xml.XmlNode In parentNode.ChildNodes(0).ChildNodes
      Dim nodePath As String = Node.Attributes("Path").Value.TrimStart("\"c)
      If nodePath.Contains("\Iteration\") Then
        AddChildNodes(nodePath.Replace("\Iteration", ""), Node, results, doNotInclude)
      ElseIf nodePath.Contains("\Area\") Then
        AddChildNodes(nodePath.Replace("\Area", ""), Node, results, doNotInclude)
      Else
        AddChildNodes(nodePath, Node, results, doNotInclude)

      End If

    Next

  End Sub


End Class
